export const useUpload = () => {
  // 用于展示的图片列表
  const fileList = ref([]);
  // 用于提交信息的字符串
  function upFile(file) {
    uni.uploadFile({
      url: config.baseUrl + "/upload/images",
      filePath: file.file.url,
      name: "file",
      header: {
        userjwttoken: uni.$sc.getToken(),
      },
      success: (res) => {
        let picRes = JSON.parse(res.data);
        if (picRes.code == 200) {
          fileList.value.push({
            url: config.baseUrl + picRes.data[0].fileUrl,
          });

          resultFile.value = fileList.value.map((it) => it.url).join(",");
        } else {
          uni.$u.toast(picRes.message);
          return false;
        }
      },
      fail: (err) => {
        uni.$u.toast("上传失败");
      },
    });
  }
  // 多选
  async function upMultipleFile(event) {
    let lists = [].concat(event.file);
    let fileListLen = fileList.value.length;
    lists.map((item) => {
      fileList.value.push({
        ...item,
        status: "uploading",
        message: "上传中",
      });
    });
    for (let i = 0; i < lists.length; i++) {
      const result = await uploadFilePromise(lists[i].url);

      if (result.success) {
        let item = fileList.value[fileListLen];
        fileList.value.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.url,
          })
        );
        fileListLen++;
      } else {
        fileList.value.splice(fileListLen, 1);
      }
    }
  }
  function uploadFilePromise(url) {
    return new Promise((resolve, reject) => {
      let a = uni.uploadFile({
        url: config.baseUrl + "/upload/images",
        filePath: url,
        // header: {
        //   userjwttoken: uni.$sc.getToken(),
        // },
        // name: "file",
        success: (uploadRes) => {
          setTimeout(() => {
            let res = JSON.parse(uploadRes.data); //最终传给的是字符串，这里需要转换格式

            if (res.code != 200) {
              uni.$sc.toast(res.msg);
              resolve({
                success: false,
                url: "",
              });
              return;
            }
            resolve({
              success: true,
              url: config.baseUrl + res.data[0].fileUrl,
            });
          }, 1000);
        },
      });
    });
  }
  function deletePic(index) {
    fileList.value.splice(index.index, 1);
  }
  const resultFile = computed(() => {
    if (fileList.value.length) {
      return fileList.value.map((it) => it.url).join(",");
    } else {
      return "";
    }
  });
  return {
    fileList,
    resultFile,
    upFile,
    upMultipleFile,
    deletePic,
  };
};
